<?php

namespace App\Http\Middleware;

use App\Facade\AppContext;
use App\Models\System\UserToken;
use App\Utils\Output;
use Closure;
use Illuminate\Support\Facades\URL;

class Login
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!AppContext::userId()) {
            if (AppContext::appId() == 2) {
                return response()->json(Output::fail(__('common.tips.login_expired'), -100));
            }
            if ($request->ajax()) {
                return response()->json(Output::fail(__('common.tips.login_expired'), -100, ['referer' => admin_url('public/login')]));
            } else {
                return redirect()->guest(admin_url('public/login') . '?referer=' . urlencode(URL::full()));
            }
        } else {
            //判断token有没有过期
            $ut = UserToken::query()->where('user_id', '=', AppContext::userId())->where('token', '=', AppContext::getToken())->first();
            if (empty($ut)) {
                if ($request->ajax()) {
                    return response()->json(Output::fail(__('common.tips.login_expired'), -100, ['referer' => admin_url('public/login')]));
                } else {
                    return redirect()->guest(admin_url('public/login') . '?referer=' . urlencode(URL::full()));
                }
            }
        }
//        list($controller, $action) = explode('@', Route::currentRouteAction());
//        if ($controller != 'App\Http\Controllers\Admin\IndexController' && !in_array($action, ['store', 'update'])) {
//            if (!\App\Utils\Auth::can($controller, $action)) {
//                if ($request->ajax()) {
//                    return Output::error('没有权限',-100, ['referer' => url('admin/login')]);
//                } else {
//                    return response('没有权限', 401);
//                }
//            }
//        }
        return $next($request);
    }
}
